﻿
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace SHKF.B2C.Mannage.Service.Controllers
{
    [Route("[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        private readonly ILogger<TestController> logger;

        public TestController(ILogger<TestController> logger)
        {
            this.logger = logger;
        }
         
        public string Get()
        {
            try
            {
                FileInfo file = new FileInfo(@"E:\SanHeKunFang\这有山图片\1107_[健驰]隐形眼镜护理液(附赠伴侣盒)150ml瓶\没加水印\UPC图.png");

                var settings = new JsonSerializerSettings
                {
                    Converters = new List<JsonConverter>
                {
                    new FileSystemInfoConverter()
                }
                };
 
                string json = JsonConvert.SerializeObject(file, settings);
            }
            catch (Exception ex)
            { 
                throw ex;
            }
           

            this.logger.LogInformation($"/TestGet {DateTime.Now}");
            return "TestController";
        }

        [HttpGet("ip")]
        public string IP()
        {
            ConnectionInfo connection = this.Request.HttpContext.Connection;

            string HostName = Dns.GetHostName();
            IPHostEntry iPHost = Dns.GetHostEntry(HostName);

            string json = iPHost.AddressList.FirstOrDefault(address => address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)?.ToString();

            //string json = $"{connection.RemoteIpAddress}:{connection.LocalPort}";


            return json;
        }
    }

    public class FileSystemInfoConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return typeof(FileSystemInfo).IsAssignableFrom(objectType);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
                return null;
            var jObject = JObject.Load(reader);
            var fullPath = jObject["FullPath"].Value<string>();
            return Activator.CreateInstance(objectType, fullPath);
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var info = value as FileSystemInfo;
            var obj = info == null
                ? null
                : new
                {
                    FullPath = info.FullName
                };
            var token = JToken.FromObject(obj);
            token.WriteTo(writer);
        }
    }

}
